package com.loooooo.pm2024.service;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.loooooo.pm2024.config.RedisUtils;
import com.loooooo.pm2024.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;

@Service
public class SmsService {

    //https://design.loooooo.com/sms/reg/code?mobile=17708434656

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    RedisUtils redisUtils;

    public void sendCode(String mobile) {
        String code = "" + (System.currentTimeMillis() % 10000);
        sendCode(mobile, code);
    }

    public void sendCode(String mobile, String code) {
        String url = String.format("https://design.loooooo.com/sms/reg/code?mobile=%s&code=%s", mobile, code);
        ResponseEntity<String> res = restTemplate.getForEntity(url, String.class);
        System.out.println(url + "\n" + res);
        ObjectNode node = JsonUtils.deserializeFromString(res.getBody(), ObjectNode.class);
        int errorCode = node.get("error_code").intValue();
        if (errorCode == 0) {
            redisUtils.set("REGCODE:" + mobile, code, Duration.ofMinutes(15));
        }
    }

    public String getCode(String mobile) {
        return redisUtils.get("REGCODE:" + mobile);
    }
}
